<script setup lang="ts">
import axios from '../axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { reactive, ref, watch } from 'vue';
import { Approver, User, RoleType, roleTypeToString} from '../model'

const props = defineProps<{
    templateId: number,
}>()

const approvers = ref<Approver[]>([])
const users = reactive<Map<number, User>>(new Map())

const approverIdSelected = ref<number>()
const candidates = ref<User[]>([])

watch(approverIdSelected, async () => {
    if (approverIdSelected.value === undefined) {
        return
    }
    const res = await axios.post(`/admin/template/approver`, {
        templateId: props.templateId,
        approverId: approverIdSelected.value,
    })
    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '选择审批人失败',
        })
        return
    }
    loadData()
})

const deleteApprover = async (approverId: number) => {
    const res = await axios.delete(`/admin/template/approver`, {
        data: {
            templateId: props.templateId,
            approverId: approverId,
        }
    })

    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '删除审批人失败',
        })
        return
    }

    loadData()

}

const swapApprover = async (approverId1: number, approverId2: number) => {
    const res = await axios.post(`/admin/template/approver/swap`, {
        templateId: props.templateId,
        approverId1: approverId1,
        approverId2: approverId2,
    })

    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '交换审批人失败',
        })
        return
    }

    loadData()

}

const loadData = async () => {
    const res = await axios.get(`/template/approver?templateId=${props.templateId}`)
    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '查询审批人列表失败',
        })
        return
    }
    approvers.value = res.data['approver']
    users.clear()
    const promises = approvers.value.map(approver => new Promise(async (resolve, reject) => {
        const res = await axios.get(`/user?userId=${approver.approverId}`)
        if (!res.data['ok']) {
            ElMessage({
                type: 'error',
                message: '查询审批人信息失败',
            })
            reject()
        }
        users.set(approver.approverId, res.data['user'])
        resolve(null)
    }))
    await Promise.all(promises)
    console.log(114)

    const res1 = await axios.get(`/admin/user`)
    if (!res1.data['ok']) {
        ElMessage({
            type: 'error',
            message: '查询用户信息失败',
        })
        return
    }

    const allUsers: User[] = res1.data['users']
    const ids = Array.from(users.keys())
    candidates.value = allUsers.filter(u => u.role == RoleType.APPROVER && ids.indexOf(u.id) == -1)
    approverIdSelected.value = undefined
}
loadData()

</script>

<template>
    <div class="approvers">
        <div class="approvers-row" v-for="approver in approvers" :key="approver.approverId">
            <div class="approver-main">
                <div class="approver-number">{{ approver.number }}.</div>
                <div class="approver-content">
                    <div class="approver-name">
                        {{ users.get(approver.approverId)?.nickname }}
                    </div>
                    <div class="approver-department">
                        {{ users.get(approver.approverId)?.department }}
                    </div>
                </div>
                <div class="approver-control">
                    <div class="approver-close" @click="() => deleteApprover(approver.approverId)">
                        <el-icon class="icon-button">
                            <close />
                        </el-icon>
                    </div>
                    <div class="approver-move">
                        <el-icon class="icon-button" v-if="approver.number != 1" @click="() => swapApprover(approver.approverId, approvers[approver.number - 2].approverId)">
                            <ArrowUp />
                        </el-icon>
                        <el-icon class="icon-button" v-if="approver.number != approvers.length" @click="() => swapApprover(approver.approverId, approvers[approver.number].approverId)">
                            <ArrowDown />
                        </el-icon>
                    </div>
                </div>
            </div>
            <el-divider />
        </div>
        <el-select
            class="approver-select"
            v-model="approverIdSelected"
            placeholder="选择要添加的审批人"
        >
            <el-option 
                v-for="approver in candidates"
                :key="approver.id"
                :label="approver.nickname"
                :value="approver.id"
            />
        </el-select>
    </div>
</template>
<style scoped>
.approvers {
  margin-bottom: 20px;
}

.approvers-row {
  display: flex;
  align-items: center;
}

.approver-main {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.approver-number {
  width: 30px;
  font-size: 16px;
  color: #606266;
  margin-right: 10px;
}

.approver-content {
  flex: 1;
}

.approver-name {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.approver-department {
  font-size: 12px;
  color: #606266;
  margin-bottom: 5px;
}

.approver-control {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.icon-button {
  font-size: 16px;
  cursor: pointer;
  margin-left: 5px;
}

.approver-select {
  width: 100%;
  margin-bottom: 20px;
  font-size: 16px;
}
</style>
